package cn.edu.sysu.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.edu.sysu.dto.ProblemDto;
import cn.edu.sysu.dto.UserDto;
import cn.edu.sysu.util.Transaction;


public enum UserDao {

	INSTANCE;

	private static String GET_ALL_USERS = "select * from cws_user where deleted = 0";


	public List<UserDto> getAllUsers(Transaction transaction) throws SQLException{
		ResultSet rs =null;
		PreparedStatement ps =null;
		try {
			transaction.begin();
			Connection conn = transaction.getResource(Connection.class);
			ps = conn.prepareStatement(GET_ALL_USERS);
			rs = ps.executeQuery();
			List<UserDto> users = new ArrayList<UserDto>();
			while(rs.next()){
				users.add(makeUserDto(transaction, rs)) ;
			}

			return users;

		} catch (SQLException se) {

			se.printStackTrace();

		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			transaction.preDestroy();
		}

		return new ArrayList<UserDto>();


	}

	private UserDto makeUserDto(Transaction transaction, ResultSet rs) throws SQLException {
		int user_id=rs.getInt(1);
		String user_name = rs.getString(2);
		String email = rs.getString(3);
		int team_id = rs.getInt(4);
		int deleted = rs.getInt(5);
		return new UserDto(user_id, team_id, user_name, email, deleted);
	}
}
